/*
 * Created on 2007-12-29
 *
 * TODO 
 */
package jacky.lanlan.song.extension.struts.mock;

import jacky.lanlan.song.extension.struts.Scope;
import jacky.lanlan.song.extension.struts.action.ValueStack;

import java.util.HashMap;
import java.util.Map;

/**
 * Mock ValueStack ，用HashMap模拟 ValueStack 语意。
 */
public class MockValueStack implements ValueStack{
	private Map<String,Object> request=new HashMap<String,Object>();
	private Map<String,Object> session=new HashMap<String,Object>();
	private Map<String,Object> context=new HashMap<String,Object>();
	
	public Object getAttribute(String name, Scope scope) {
		switch (scope) {
			case Request:
				return request.get(name);
			case Session:
				return session.get(name);
			case ServletContext:
				return context.get(name);
		}
		return null;
	}

	public Object getAttribute(String name) {
		Object value=null;
		for(Scope scope:Scope.values()) {//values是按Scope元素的声明顺序返回的数组，符合该方法的语意
			value=this.getAttribute(name, scope);
			if(value!=null) {
				return value;
			}
		}
		return value;
	}

	public void removeAttribute(String name, Scope scope) {
		//没有Ruby的“Duck Type”，switch无法抽到一个方法里面，该死的Java啊
		switch (scope) {
			case Request:
				request.remove(name);
				break;
			case Session:
				session.remove(name);
				break;
			case ServletContext:
				context.remove(name);
		}
	}

	public void setAttribute(String name, Object value, Scope scope) {
		switch (scope) {
			case Request:
				request.put(name,value);
				break;
			case Session:
				session.put(name,value);
				break;
			case ServletContext:
				context.put(name,value);
		}
	}
	
	public void setAttribute(String name, Object value) {
		request.put(name, value);
	}
	
	public String getRequestParameter(String name) {
		return (String) request.get(name);
	}
	
}